package com.xigege.nio.bufferAndChannel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author huangxi
 * @class NIOFileChannelTransferToFile
 * @description NIOFileChannelTransferToFile
 * @create 2022-08-15 11:06
 */
public class NIOFileChannelTransferToFile {
    public static void main(String[] args) throws IOException {
        transferToDemo();
    }

    private static void walkFileTreeDemo() throws IOException {
        Path path = Paths.get("/Users/hx/IdeaProjects/netty_chat");
        AtomicInteger dirNum = new AtomicInteger();
        AtomicInteger fileNum = new AtomicInteger();

        Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                dirNum.incrementAndGet();
                System.out.println(dir);
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                fileNum.incrementAndGet();
                System.out.println(file);
                return super.visitFile(file, attrs);
            }
        });

        System.out.println("文件夹数量：" + dirNum);
        System.out.println("文件数量：" + fileNum);
    }

    /**
     * transferTo不能传输超过2G的文件，需要分块传输
     *
     * @throws IOException
     */
    private static void trunkTransferTo() throws IOException {
        FileInputStream fis = new FileInputStream("/Users/hx/IdeaProjects/netty_chat/pom.xml");
        FileOutputStream fos = new FileOutputStream("/Users/hx/IdeaProjects/netty_chat/pom_transfer.xml");

        FileChannel fisChannel = fis.getChannel();
        FileChannel fosChannel = fos.getChannel();

        long size = fisChannel.size();
        for (long surplus = size; surplus > 0; ) {
            surplus = surplus - fisChannel.transferTo((size - surplus), size, fosChannel);
        }

        fis.close();
        fos.close();

        fosChannel.close();
        fisChannel.close();
    }

    private static void transferToDemo() throws IOException {
        FileInputStream fis = new FileInputStream("/Users/hx/IdeaProjects/netty_chat/pom.xml");
        FileOutputStream fos = new FileOutputStream("/Users/hx/IdeaProjects/netty_chat/pom_transfer.xml");

        FileChannel fisChannel = fis.getChannel();
        FileChannel fosChannel = fos.getChannel();

        fisChannel.transferTo(0, fisChannel.size(), fosChannel);

        fis.close();
        fos.close();

        fosChannel.close();
        fisChannel.close();
    }


}
